const Router = require("@koa/router");
const router = new Router();
const startConnect = require("../db");
const Auth = require("../middlewares/auth");
const {
  generateToken,
  encryptPwd,
  decodePwd,
  verifyToken,
} = require("../core/util");

//验证是否已有该用户名
router.get("/has_user", async (ctx) => {
  const { username } = ctx.request.query;

  const sql = `select username from user where username = '${username}'`;
  await startConnect(sql).then((res) => {
    ctx.body = {
      tag: res[0] ? true : false,
    };
    console.log("hasUser");
  });
});

//验证密码
router.post("/verify_pwd", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  console.log("isvalid", isValid);
  if (isValid) {
    const { id } = isValid;
    const { password } = ctx.request.body;

    const sql = `select password from user where id = '${id}'`;

    await startConnect(sql).then(async (res) => {
      if (res[0]) {
        const pwd = decodePwd(res[0].password);
        ctx.body = {
          tag: pwd === password,
        };
        console.log("验证密码", isValid, password);
      } else {
        ctx.body = {
          tag: false,
        };
      }
    });
  } else {
    ctx.body = 404;
  }
});

//修改密码
router.post("/change_pwd", async (ctx) => {
  const isValid = verifyToken(ctx.headers.authorization);
  console.log("isvalid", isValid);
  if (isValid) {
    const { id } = isValid;
    const { password } = ctx.request.body;

    const sql = `update user set password='${encryptPwd(
      password
    )}'  where id = '${id}'`;
    console.log("修改密码", isValid, password);
    await startConnect(sql).then((res) => {
      console.log("res", res);
      ctx.body = {
        tag: res.affectedRows,
      };
    });
  } else {
    ctx.body = 404;
  }
});

//登录
router.post("/login", async (ctx) => {
  const body = ctx.request.body;
  const { username, password } = body;

  const sql = `select password,id,state from user where username = '${username}' `;

  await startConnect(sql).then(async (res) => {
    console.log("res", res);
    if (res[0]) {
      const pwd = decodePwd(res[0].password);
      console.log("pwd", pwd);
      if (pwd === password) {
        if (res[0].state) {
          console.log("pwd", pwd);
          const scope = username === "admin" ? 1 : 0;
          ctx.body = {
            tag: true,
            token: generateToken(res[0].id, scope),
          };
        } else {
          ctx.body = {
            tag: false,
            msg: "该账户已被封禁",
          };
        }
      } else {
        ctx.body = {
          tag: false,
        };
      }
    } else {
      ctx.body = {
        tag: false,
      };
    }
  });
});

//注册
router.post("/register", async (ctx) => {
  const body = ctx.request.body;

  const { username, password } = body;

  const sql = `insert into user (username,password) values('${username}','${encryptPwd(
    password
  )}')`;
  console.log("register", body);

  await startConnect(sql).then((res) => {
    ctx.body = {
      msg: "注册",
      tag: res.affectedRows,
    };
  });
});

module.exports = router;
